import random
import time
import uuid

import requests
import hashlib
import base64

class SMS:
    def __init__(self,acount_sid,auth_token,appid,template_id):
        self.acount_sid = acount_sid
        self.auth_token = auth_token
        self.appid = appid
        self.template_id = template_id

    def get_url(self):
        url=f"https://app.cloopen.com:8883/2013-12-26/Accounts/{self.acount_sid}/SMS/TemplateSMS?sig={self.get_sig()}"
        return url
    def get_sig(self):

        # 2c6eef3fd1fa4acc9225f825bd640f93

        sig =hashlib.md5((f"{self.acount_sid}{self.auth_token}{time.strftime('%Y%m%d%H%M%S')}").encode()).hexdigest()
        s=sig.upper()
        print(s)
        return s

    def get_headers(self):
        s=self.acount_sid+':'+ time.strftime('%Y%m%d%H%M%S')
        auth=base64.b64encode(s.encode()).decode()
        return {
            "Accept":"application/json;",
            "Content-Type": "application/json;charset=utf-8;",
            # Content - Length: 256;
            "Authorization":auth,
        }
    def get_body(self,phone,code):
        return  {"to":phone,
                 "appId":self.appid,
                                "subAppend":"8888",
                 "templateId":self.template_id,"datas":[code,10]}

    def send_sms(self, phone, code):
        url = self.get_url()
        headers = self.get_headers()
        data = self.get_body(phone, code)
        response = requests.post(url=url, headers=headers, json=data)

        # 打印响应状态码和内容
        print("Status Code:", response.status_code)
        print("Response Content:", response.text)

        # 如果响应内容是 JSON，则解析
        try:
            return response.json()
        except ValueError:
            # 如果响应不是 JSON，返回原始内容
            return response.text
if __name__ == '__main__':
    config={
        "acount_sid":"2c94811c9416ed01019468603b0d0e5a",
        "auth_token":"2c6eef3fd1fa4acc9225f825bd640f93",
        "appid":"2c94811c9416ed01019468603ce10e61",
        "template_id":"1"
    }
    sms= SMS(**config)
    code=random.randint(1000,9999)
    print(sms.send_sms("15831601783",code))



